package com.ndp.fb.creative.fetchdata.dao.mysql.impl;

import com.ndp.fb.creative.fetchdata.dao.domain.Image;
import com.ndp.fb.creative.fetchdata.dao.mysql.AccountImageRdbService;
import com.ndp.fb.creative.fetchdata.dao.mysql.DaoTemplate;
import com.ndp.fb.creative.fetchdata.dao.mysql.impl.mapper.HashCodeRowMapper;
import com.ndp.fb.creative.fetchdata.dao.mysql.impl.mapper.IdListRowMapper;
import com.ndp.fb.creative.fetchdata.dao.mysql.impl.mapper.StringListRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Jacky on 2015/1/31.
 */
@Service
public class AccountImageRdbServiceImpl extends DaoTemplate implements AccountImageRdbService {

    @Autowired
    private HashCodeRowMapper rowMapper;

    @Autowired
    private IdListRowMapper idListRowMapper;

    @Autowired
    private StringListRowMapper stringListRowMapper;


    @Override
    public List<Image> getHashCodeByName(String name)
    {
        String sql = "SELECT t.id,t.image_id,t.name,t.hash_code,a.visit_path,a.lit_img_url FROM account_images t JOIN adimage a ON t.image_id = a.id WHERE t.hash_code <> '' AND t.name=? GROUP BY t.hash_code";
        return getJdbcTemplate().query(sql, rowMapper, name);
    }

    @Override
    public List<Image> getHashCodeByHash(String hash)
    {
        String sql = "SELECT t.id,t.image_id,t.name,t.hash_code,a.visit_path,a.lit_img_url FROM account_images t JOIN adimage a ON t.image_id = a.id WHERE t.hash_code <> '' AND t.hash_code=? GROUP BY t.hash_code";
        return getJdbcTemplate().query(sql, rowMapper, hash);
    }

    @Override
    public List<String> getNamesByHash(String hash)
    {
        String sql = "SELECT DISTINCT(t.name) FROM account_images t where t.hash_code=?";
        return getJdbcTemplate().query(sql, stringListRowMapper, hash);
    }

    @Override
    public List<Image> getHashCodeByNames(String names)
    {
        String sql = "SELECT t.id,t.image_id,t.name,t.hash_code,a.visit_path,a.lit_img_url FROM account_images t JOIN adimage a ON t.image_id = a.id  WHERE t.hash_code <> '' AND t.name IN (?) GROUP BY t.hash_code";
        logger.info(sql);
        return getJdbcTemplate().query(sql, rowMapper, names);
    }

    @Override
    public List<Long> getAdGroupIdsByHashCode(String hashCode)
    {
        String sql = "SELECT b.ad_group_id FROM ad_group b WHERE b.ad_creative_id IN (SELECT a.ad_creative_id FROM ad_creative a WHERE a.object_story_spec LIKE ?)";
        logger.info(sql);
        return getJdbcTemplate().query(sql, idListRowMapper , "%"+hashCode+"%");
    }

    @Override
    public List<String> getHashCodeByFburl(String fbUrl)
    {
        String sql = "SELECT t.hash_code FROM account_images t WHERE  t.fb_url=?";
        //return getJdbcTemplate().query(sql, , fbUrl);
        return null;
    }


}
